package com.bupt.vueblog.controller;

import com.bupt.vueblog.constant.Message;
import com.bupt.vueblog.constant.Result;
import com.bupt.vueblog.constant.Status;
import com.bupt.vueblog.domain.dto.UserChangeDTO;
import com.bupt.vueblog.domain.entity.User;
import com.bupt.vueblog.domain.dto.UserDTO;
import com.bupt.vueblog.domain.vo.UserVO;
import com.bupt.vueblog.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 谭继好
 * @Description
 * @date 2024-04-10 14:57
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public Result<UserVO> login(@RequestBody UserDTO userDTO) {
        User user = userService.getByName(userDTO.getUsername());
        if (ObjectUtils.isEmpty(user)) {
            return Result.fail(Status.NOT_SIGN_UP, Message.NOT_SIGN_UP);
        } else if (!user.getPassword().equals(userDTO.getPassword())) {
            return Result.fail(Status.WRONG_PASSWORD, Message.WRONG_PASSWORD);
        }
        // 返回信息时只返回id和名字，密码不返回，保证数据安全，前端也用不着
        UserVO res = new UserVO();
        BeanUtils.copyProperties(user, res);
        return Result.success(res);
    }

    @PostMapping("/add")
    public Result addUser(@RequestBody UserDTO userDTO) {
        try {
            // 用户名可能重复，所以捕获异常
            userService.insert(userDTO);
        } catch (Exception e) {
            return Result.fail(Status.EXIST_NAME, Message.EXIST_NAME);
        }
        return Result.success();
    }

    @PutMapping
    // 修改用户名和修改密码合二为一，如果修改密码要判断密码是否正确
    // 可能出现用户名重复的情况，所以捕获一下异常，返回提示信息
    public Result changeUser(@RequestBody UserChangeDTO user) {
        if (!StringUtils.isEmpty(user.getOldPwd())) {
            User res = userService.getById(user.getId());
            if (!res.getPassword().equals(user.getOldPwd())) {
                return Result.fail(Status.WRONG_PWD, Message.WRONG_PWD);
            }
        }
        try {
            userService.change(user);
        } catch (Exception e) {
            return Result.fail(Status.EXIST_NAME, Message.EXIST_NAME);
        }
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable int id) {
        userService.delete(id);
        return Result.success();
    }
}
